/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package engine;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JApplet;

import gui.*;
import java.sql.SQLException;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
 *
 * @author Puma
 */
public class engine extends JApplet{
    
    /*
     * email, jelszo, adatbazis
     */
    private String email;
    private String pw;
    private String url = "jdbc:oracle:thin:@localhost:1521";
    
    /*
     * betegkent jelentkeztunk-e be
     */
    private boolean beteg;
    
    /*
     * a kortortenetben maszkalashoz az adott beteg azonositoja
     */
    private String vizsgaltBetegTAJ;
    
    /*
     * az orvos azonositoja, akinel az idopontot felvennenk
     */
    private String idopont_orvos_EOA;
            
    private Connection con;
    private PreparedStatement stmt;
    ResultSet resultset;
            
    top_applet applet;
    
	/**
	 * Returns the value of the named parameter in the HTML tag. (In case of a
	 * standalone application, returns the system property indicated by the
	 * specified key.)
	 */
    private boolean isStandalone = false;
	public String getParameter(String key, String def) {
		return isStandalone ? System.getProperty(key, def)
				: (getParameter(key) != null ? getParameter(key) : def);
	}
    public engine(top_applet _applet) throws SQLException{
        super();
        applet = _applet;
        String driverName = applet.getParameter("driverName", "oracle.jdbc.driver.OracleDriver");
        try {
                Class.forName(driverName);
                //print(driverName + " loaded.");
        } catch (ClassNotFoundException e) {
                //print(driverName + " not found.");
                return;
        }
        if (java.lang.System.getProperty("java.vendor").equals("Microsoft Corp.")) {
                DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
        }

        url = applet.getParameter("url", "jdbc:oracle:thin:@localhost:1521");
    }
    
    /*
     * Kozos cuccok - mind a beteg, mind az orvos eseten mukodnek
     */
    
    public String getSzerep(){
        return beteg ? "beteg" : "orvos";
    }
    
    public int reg(String email, String p1, String p2, boolean b, String EAO, String TAJ, String lazonosito){
        if((lazonosito==null && b) || email==null || p1==null || (EAO==null && b) || (TAJ==null && b))
            return -1;
        if(email.length()==0 || p1.length()==0 || p2.length()==0)
            return -1;
        if(b && TAJ.length()==0 && lazonosito.length()==0)
            return -1;
        if(!b && EAO.length()==0)
            return -1;
        
        try{
            
            con = DriverManager.getConnection(url, "eportal", "admin"); // felhasznalonev es jelszo
            if(b){
                stmt = con.prepareStatement(
                        "insert into beteg values (?, ?, ?, ?)");
                stmt.setString(1, email);
                stmt.setString(2, p1);
                stmt.setString(3, TAJ);
                stmt.setString(4, lazonosito);
            }
            else{
                stmt = con.prepareStatement(
                        "insert into orvos values (?, ?, ?, ?)");
                stmt.setString(1, email);
                stmt.setString(2, p1);
                stmt.setString(3, "9-18");
                stmt.setString(4, EAO);
            }
            resultset = stmt.executeQuery();
        }catch(Exception e){e.printStackTrace(); return -1;}
        
        return 0;
    }
    
    /*
     * Visszateresi ertek:
     * SIKER:
     * beteg eseten 1
     * orvos eseten 2
     * HIBA:
     * -1
     */
    public int login(String u, String p, Boolean b){
        
        String szerep;
        String szemelyesAdat;
        boolean talalt;
        if(b){
            szerep = "beteg";
            szemelyesAdat = "taj";
        }
        else{
            szerep = "orvos";
            szemelyesAdat = "eoa";
        }
        try{
            System.out.println("lofasz");
            con = DriverManager.getConnection(url, "eportal", "admin"); // felhasznalonev es jelszo
            stmt = con.prepareStatement(
                    "select email, jelszo, "+ szemelyesAdat +" from "+ szerep +" where email = ?");  
            stmt.setString(1, u);
            resultset = stmt.executeQuery();
            System.out.println("lofasz2");
            talalt = false;
            while(resultset.next()){
                System.out.println("lofasz3");
                String pw1 = resultset.getString(2);
                if(p.equals((String)pw1)){
                    email = u;
                    pw = p;
                    beteg = b;
                    String s = resultset.getString(3);
                    if(b)
                        this.vizsgaltBetegTAJ = s;
                    else
                        this.idopont_orvos_EOA = s;
                    talalt = true;
                }
            }            
            
            if(!talalt)
                return -1;

            if(b)
                return 1;
            else
                return 2;
        }catch(Exception e){e.printStackTrace(); return -1;}
    }
    
    /*
     * kijelentkezeskor mindent nullazunk
     */
    
    public void logout(){
        email = null;
        pw = null;
        beteg = false;
        vizsgaltBetegTAJ = null;
        idopont_orvos_EOA = null;
        try{
            con.close();
        }catch(Exception e){}
    }
    
    /*
     * a fooldal felso soraba kiirandó "Udvoozoljuk, XY"-hoz a nev
     */
    public String getWelcomeName(){
        String result = "Ismeretlen";
        try{
            if(beteg){
                stmt = con.prepareStatement(
                    "select tnev from szemely where taj = ?");  
                stmt.setString(1, this.vizsgaltBetegTAJ);
            }
            else{
                stmt = con.prepareStatement(
                    "select tnev from odb where eoa = ?");  
                stmt.setString(1, this.idopont_orvos_EOA);
            }
            resultset = stmt.executeQuery();
            while(resultset.next()){
                result = resultset.getString(1);
            }
        }catch(Exception e){e.printStackTrace();}
        return result;
    }
    
    /*
     * beallitjuk a kortortenetben matatashoz a TAJ-t
     */
    public void setVizsgaltTAJ(String b){
        vizsgaltBetegTAJ = b;
    }
    
    /*
     * megkapjuk a beallitott TAJ szamhoz a kortortenetet
     */
    public ArrayList<String> getKortortenet(){
        ArrayList<String> result = new ArrayList<String>();
        try{
            stmt = con.prepareStatement(
                    "select kortort, kazonosito from eek where taj = ?");  
            stmt.setString(1, this.vizsgaltBetegTAJ);
            resultset = stmt.executeQuery();
            while(resultset.next()){
                result.add(resultset.getString(1));
            }
        }catch(Exception e){e.printStackTrace();}
        return result;
    }
    
    /*
     * megkapjuk a beallitott orvos szabad idopontjait
     */
    public ArrayList<String> getIdopontok(){
        ArrayList<String> tolig = this.getRendelesiIdo();
        if(tolig.size()<2)
            return new ArrayList<String>();
        int tol = Integer.parseInt(tolig.get(0).split(":")[0]);
        int ig = Integer.parseInt(tolig.get(1).split(":")[0]);
        
        ArrayList<String> foglalt = this.getFoglaltIdopontok();
        int foglaltakt = 0;
        
        ArrayList<String> osszes = new ArrayList<String>();
        
        int NAPOK = 21;
        
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        for(int nap = 0; nap<NAPOK; nap++){
            cal.add(Calendar.DAY_OF_YEAR, 1);
            if(cal.get(Calendar.DAY_OF_WEEK)<Calendar.SATURDAY &&
                    cal.get(Calendar.DAY_OF_WEEK)>Calendar.SUNDAY)
                for(int ora = tol; ora<ig; ora++){
                    cal.set(Calendar.HOUR_OF_DAY, ora);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String akt = sdf.format(cal.getTime());
                    if(foglalt!=null && foglalt.size()>foglaltakt && foglalt.get(foglaltakt).contains(akt)){
                        foglaltakt++;
                    }else{
                        osszes.add(akt);                        
                    }
                }
        }
        return osszes;
    }    
    
    /*
     * Idopont foglalas, es 2 email kikuldese.
     * Elso parameter: az idopont sorszama (1 oras intervallumok; 
     * a tol-ig hatarok ismertek -> kimatekozhato
     * Masodik parameter: ha orvos vagyok, akkor ki kell valasztanom a beteget
     * Harmadik parameter: ha orvos vagyok, beirhatok a betegnek egy masik 
     * emailt, amit telefonban kert (a beteg nincs 
     * feltetlenul regisztralva -> nem ismert az email cime
     */
    public int setIdopont(String i, String taj, String email){
        if(i==null || i.length()<10)
            return -1;
        String email1="a", email2="b";
        try{
            stmt = con.prepareStatement(
                    "select orvos.email from orvos where eoa = ?");  
            stmt.setString(1, this.idopont_orvos_EOA);
            resultset = stmt.executeQuery();
            while(resultset.next()){
                email2 = resultset.getString(1);
            }
        }catch(Exception e){e.printStackTrace();}
        if(beteg){
            try{
                stmt = con.prepareStatement(
                        "select email from beteg where taj = ?");  
                stmt.setString(1, this.vizsgaltBetegTAJ);
                resultset = stmt.executeQuery();
                while(resultset.next()){
                    email1 = resultset.getString(1);
                }
            }catch(Exception e){e.printStackTrace();}
        }
        else{
            email1 = email;
        }
        
        try{
            stmt = con.prepareStatement(
                    "insert into foglalas values (?, ?, ?)");  
                stmt.setString(1, email1);
                stmt.setString(2, email2);
                stmt.setTimestamp(3, Timestamp.valueOf(i));
            resultset = stmt.executeQuery();
        }catch(Exception e){e.printStackTrace();}
        
        String idopont = i;
        sendEmail(idopont,email1,email2);
        return 0;
    }
    
    /*
     * megerosito email a foglalasrol
     * az emailcimeket megkapjuk; az emailbe beleirando neveket pedig kihalasszuk az adatbazisbol
     */
    private void sendEmail(String idopont, String email1, String email2){
        String betegnev = email1;
        
        try{
            stmt = con.prepareStatement(
                    "select szemely.tnev from szemely where szemely.taj = ?");  
            stmt.setString(1, this.vizsgaltBetegTAJ);
            resultset = stmt.executeQuery();
            while(resultset.next()){
                betegnev = resultset.getString(1);
            }
        }catch(Exception e){e.printStackTrace();}
        
        String orvosnev = email2;
        
        try{
            stmt = con.prepareStatement(
                    "select tnev from odb where eoa = ?");  
            stmt.setString(1, this.idopont_orvos_EOA);
            resultset = stmt.executeQuery();
            while(resultset.next()){
                orvosnev = resultset.getString(1);
            }
        }catch(Exception e){e.printStackTrace();}
        
        
        String host = "smtp.gmail.com";
        final String from = "euportal.szoftarch@gmail.com";
        final String pw = "euportal";
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pw);
        props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
        props.put("mail.smtp.auth", "true");
        
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(from, pw);
			}
		  });
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email1));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email2));
            message.setSubject("EUportal idopont foglalas ertesito");
            message.setText("Foglalt idopont: " + idopont + "\nBeteg: " + betegnev + "\nOrvos: " + orvosnev);
        
            Transport.send(message);
        }catch(Exception e){e.printStackTrace();}
        
    }
    
    /*
     * Orvos altal hasznalhato cuccok
     */
    
    /*
     * adott sorszamu kortorteneti bejegyzes elkerese a korabban beallitott 
     * betegrol az orvosnak
     */
    public ArrayList<String> getKorElem(int i){
        ArrayList<String> elem = new ArrayList<String>();
        try{
            stmt = con.prepareStatement(
                    "select kortort, kazonosito from eek where taj = ? order by kazonosito");  
            stmt.setString(1, this.vizsgaltBetegTAJ);
            resultset = stmt.executeQuery();
            int tmp = 0;
            while(resultset.next()){
                if(tmp==i){
                    elem.add(resultset.getString(2));
                    elem.add(resultset.getString(1));
                    return elem;                
                }
                tmp++;
            }
        }catch(Exception e){e.printStackTrace();}
        elem.add("Hiba");
        elem.add("A kért elem nem található");
        return elem;
    }
    
    /*
     * uj korelem hozzaadasa a korabban beallitott beteghez
     */
    public int addKorElem(String elem){
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String azon = sdf.format(cal.getTime());
        System.out.println(azon);
        int siker = -1;
        try{
            stmt = con.prepareStatement(
                    "insert into eek values (?, ?, ?)");  
            stmt.setString(1, this.vizsgaltBetegTAJ);
            stmt.setString(2, azon);
            stmt.setString(3, elem);
            resultset = stmt.executeQuery();
            while(resultset.next()){
                siker = 0;
            }
        }catch(Exception e){e.printStackTrace();}
        return siker;
    }
    
    /*
     * kivalasztott korelem torlese.
     * a sorszama alapjan kikeresheto az elore beallitott 
     * beteg kortortenetenek lekerdezesebol
     */
    public int removeKorElem(String azon){
        int siker = -1;
        try{
            stmt = con.prepareStatement(
                    "delete from eek where kazonosito = ?");  
            stmt.setString(1, azon);
            resultset = stmt.executeQuery();
            while(resultset.next()){
                siker = 0;
            }
        }catch(Exception e){e.printStackTrace();}
        return siker;
    }
    
    /*
     * kivalasztott korelem atirasa
     */
    public int editKorElem(String azon, String elem){
        int siker = -1;
        try{
            stmt = con.prepareStatement(
                    "update eek set kortort = ? where kazonosito = ?");  
            stmt.setString(1, elem);
            stmt.setString(2, azon);
            resultset = stmt.executeQuery();
            con.commit();
            while(resultset.next()){
                siker = 0;
            }
        }catch(Exception e){e.printStackTrace();}
        return siker;
    }
    
    /*
     * rendelesi ido kibanyaszasa az orvosnal.
     */
    public ArrayList<String> getRendelesiIdo(){
        ArrayList<String> rido = new ArrayList<String>();
        try{
            stmt = con.prepareStatement(
                    "select rido from orvos where eoa = ?");  
            stmt.setString(1, this.idopont_orvos_EOA);
            resultset = stmt.executeQuery();
            while(resultset.next()){
                String tmp = resultset.getString(1);
                String tol = tmp.split("-")[0];
                String ig = tmp.split("-")[1];
                rido.add(tol+":00");
                rido.add(ig+":00");
            }
        }catch(Exception e){e.printStackTrace();}
        return rido;
    }
    
    /*
     * rendelesi ido beallitasa az orvosnal.
     * 1:00 formatumbol kell 1-et csinalni
     */
    public int setRendelesiIdo(String tol, String ig){
        int siker = -1;
        String tol1 = tol.split(":")[0];
        String ig1 = ig.split(":")[0];
        int kezdes = Integer.parseInt(tol1);
        int vegzes = Integer.parseInt(ig1);
        if(kezdes>23 || kezdes<0 || vegzes>24 || vegzes<1){
            return siker;
        }
        try{
            stmt = con.prepareStatement(
                    "update orvos set rido = ? where eoa = ?");  
            stmt.setString(1, Integer.toString(kezdes)+"-"+Integer.toString(vegzes));
            stmt.setString(2, this.idopont_orvos_EOA);
            resultset = stmt.executeQuery();
            while(resultset.next()){
                siker = 0;
            }
        }catch(Exception e){e.printStackTrace();}
        return siker;
    }
    
    /*
     * megkapjuk a foglalt idopontjainkat
     * formatum: yyyy-mm-dd hh:mm:ss
     * nanosecundumok is lennenek a Timestampben, de levagjuk
     */
    public ArrayList<String> getFoglaltIdopontok(){
        ArrayList<String> foglalt = new ArrayList<String>();
        try{
            stmt = con.prepareStatement(
                    "select foglalas.idopont from foglalas, orvos where orvos.email = foglalas.orvos AND orvos.EOA = ? order by foglalas.idopont");   
            stmt.setString(1, this.idopont_orvos_EOA);
            resultset = stmt.executeQuery();
            while(resultset.next()){
                String tmp = resultset.getTimestamp(1).toString();
                foglalt.add(tmp);
            }
        }catch(Exception e){e.printStackTrace();}
        return foglalt;
    }
    
    /*
     * Beteg altal hasznalhato cuccok
     */
    
    /*
     * orvosok listaja, idopont foglalashoz a betegnek
     */
    public ArrayList<String> getOrvosok(){
        ArrayList<String> result = new ArrayList<String>();
        try{
            stmt = con.prepareStatement(
                    "select odb.tnev, odb.szakter from odb, orvos where odb.eoa = orvos.eoa order by tnev");  
            resultset = stmt.executeQuery();
            while(resultset.next()){
                result.add(resultset.getString(1)+" - "+resultset.getString(2));
            }
        }catch(Exception e){e.printStackTrace();}
        return result;
    }
    
    /*
     * orvos beallitasa idopontfoglalashoz - listabeli index alapjan
     */    
    public void setOrvos(int o){
        ArrayList<String> orvosok = new ArrayList<String>();
        try{
            stmt = con.prepareStatement(
                    "select odb.tnev, odb.eoa from odb, orvos where odb.eoa = orvos.eoa order by tnev");   
            resultset = stmt.executeQuery();
            while(resultset.next()){
                orvosok.add(resultset.getString(2));
            }
        }catch(Exception e){e.printStackTrace();}
        idopont_orvos_EOA = orvosok.get(o);
    }
    
    /*
     * megkapjuk a foglalt idopontjainkat, betegkent
     * formatum: yyyy-mm-dd hh:mm:ss
     * nanosecundumok is lennenek a Timestampben, de levagjuk
     */
    public ArrayList<String> getBetegIdopontok(){
        ArrayList<String> foglalt = new ArrayList<String>();
        try{
            stmt = con.prepareStatement(
                    "select foglalas.idopont from foglalas, beteg where beteg.email = foglalas.beteg AND beteg.TAJ = ? order by foglalas.idopont");   
            stmt.setString(1, this.vizsgaltBetegTAJ);
            resultset = stmt.executeQuery();
            while(resultset.next()){
                String tmp = resultset.getTimestamp(1).toString();
                foglalt.add(tmp);
            }
        }catch(Exception e){e.printStackTrace();}
        return foglalt;
    }
    
}
